<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_V2_System
{

    /**
     * 文章类的typeid
     */
    public static $article_type_ids = array(4, 101, 115);

    public static function get_model_type_list()
    {
        $sql = "SELECT id,modulename,pinyin,issystem,isopen FROM sline_model";
        return DB::query(Database::SELECT, $sql)->execute()->as_array();
    }

    /*
     * 将相对文件url换成绝对文件url
     */
    public static function reorganized_resource_url($url)
    {
        if (!empty($url)) {
            $http  = stripos(strtolower($url), 'http://');
            $https = stripos(strtolower($url), 'https://');
            if ($http === false && $https === false) {
                if (substr($url, 0, 8) == '/uploads') {
                    return common::get_main_host() . $url;
                } elseif (substr($url, 0, 7) == 'uploads') {
                    return common::get_main_host() . '/' . $url;
                } elseif (substr($url, 0, 2) == '//') {
                    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https:' : 'http:';
                    return $http_type . $url;
                } elseif (substr($url, 0, 4) == '/res') {
                    return common::get_main_host() . $url;
                } elseif (stripos($url, 'h5') !== false) {
                    return common::get_main_host() . '/' . $url;
                }
            } else {
                return $url;
            }
        }
        return $url;
    }

    /**
     * @function uniapp图片获取 （目前会出现的问题为，地址无协议情况）
     * @param $url
     * @param string $w
     * @param string $h
     * @return string
     */
    public static function uniapp_img($url, $w = '', $h = '')
    {
        $path = Common::img($url, $w, $h);
        $path = self::reorganized_resource_url($path);
        return $path;
    }

    /**
     * @function 获取产品图片列表
     * @param $picStr
     * @return array
     */
    public static function get_product_piclist($picStr)
    {
        if (empty($picStr)) {
            return array();
        }

        $newArr = array();
        $arr    = explode(',', $picStr);
        foreach ($arr as &$v) {
            $v = explode('||', $v);
            // 获取图片路径
            $pi = Model_Api_V2_System::uniapp_img($v[0], 750, 400);
            array_push($newArr, $pi);
        }
        return $newArr;
    }

    /*
     * 将unix时间戳换成可识别时间字符串
     */
    public static function format_unixtime($unix_time)
    {
        return ($unix_time ? date("Y-m-d H:i:s", $unix_time) : "");
    }

    /**
     * 获取系统参数值
     */
    public static function get_sys_para($varname)
    {
        $v = DB::select('value')->from('sysconfig')->where('varname', '=', $varname)->and_where('webid', '=',
            0)->execute()->get('value');

        return $v ? $v : '';
    }

    /**
     * 获取分销配置参数值
     */
    public static function get_fenxiao_para($varname)
    {
        if ($varname == 'cfg_wxxcx_appid') {
            $appkey = Model_Sysconfig::get_sys_conf('value', 'cfg_global_client_appkey');
            if ($appkey) {
                return $appkey;
            }
        }
        if ($varname == 'cfg_wxxcx_appsecret') {
            $appsecret = Model_Sysconfig::get_sys_conf('value', 'cfg_global_client_appsecret');
            if ($appsecret) {
                return $appsecret;
            }
        }
        $v = DB::select('value')->from('fenxiao_config')->where('varname', '=', $varname)->execute()->get('value');
        return $v ? $v : '';
    }

    /**
     * @function 获取星期
     * @param $day
     * @return mixed
     */
    public static function get_weekday($day)
    {
        $w = date('w', $day);
        //注意上面返回的都是 数字,0123456.所以如果要显示中文的星期，可以定义下面的数组就可以了。
        $weekarray = array("日", "一", "二", "三", "四", "五", "六"); //0表示星期日
        return $weekarray[$w];
    }


    /**
     * @function 获取产品的保险信息
     * @param int $id 产品ID
     * @param int $typeid 产品类型ID
     * @return mixed
     */
    public static function get_insurance($productid, $typeid)
    {
        $plan_list = array();

        if (St_Functions::is_system_app_install(111)) {
            $lineday  = DB::select('lineday')->from('line')->where('id', '=', $productid)->execute()->get('lineday');
            $planlist = Model_Insurance_Base::get_add_product_list($typeid, $productid);
            foreach ($planlist as &$plan) {
                $planinfo                       = Model_Insurance_Base::get_plan_info_default($plan['planid']);
                $plan['insuranceagename']       = $planinfo['insuranceagename'];
                $plan['insuranceexpiresidname'] = $planinfo['insuranceexpiresidname'];
                $plan['productlist']            = $planinfo['productlist'];
                $price                          = Model_Insurance_Base::get_product_plan_price($planinfo['price'], $planinfo['unit_price'],
                    $lineday);
                $plan['price']                  = Currency_Tool::price($price);
                $highday                        = DB::select('highday')->from('insurance_expires')->where('id', '=',
                    $planinfo['expiresid'])->execute()->get('highday');
                if (!($lineday > $highday) && $plan['price']) {
                    $plan_list [] = $plan;
                }
            }
        }

        return $plan_list;
    }

    /**
     * 栏目获取首页类型
     * @param $typeid
     * @return mixed
     */
    public static function get_index_attr($typeid)
    {
        if ($typeid == 1) {
            $table = 'line_attr';
        } elseif ($typeid == 2) {
            $table = 'hotel_attr';
        } elseif ($typeid == 3) {
            $table = 'car_attr';
        } elseif ($typeid == 5) {
            $table = 'spot_attr';
        }
        $id = DB::select('id')->from($table)->where('pid', '=', '0')
            ->and_where('isopen', '=', '1')->limit(1)->execute()->get('id');

        $arr = DB::select('id', 'pid', 'attrname')->from($table)->where('pid', '=', $id)->and_where('isopen', '=', '1')
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->limit(9)->execute()->as_array();

        return $arr;
    }

    /**
     * @function 获取小程序权限
     * @param $mini_type 1 三方平台小程序(需要检查是否是组合小程序) 2 独立小程序
     * @param $siteId
     * @param $secret
     * @return array
     */
    public static function get_xcx_auth($mini_type, $siteId, $secret)
    {
        $tag_type = 1; // 1 综合版本 2 组合小程序
        if ($mini_type == 1) {
            // 检查小程序是否是组合小程序并进行权限控制
            $mini_auth = self::get_app_auth($siteId, $secret);
            if (isset($mini_auth['appInfo']) && $mini_auth['appInfo']) {
                $tag_type = $mini_auth['appInfo']['type'];
            }
        }

        $result = array();
        if ($tag_type == 2) {
            $auth = $mini_auth['appInfo']['auth'];
            foreach ($auth as $v) {
                array_push($result, $v['update_ProductCode']);
            }
        } else {
            $product = DB::select('productcode')->from('app')->where('system_part_type', '=', 2)->execute()->as_array();
            foreach ($product as $item) {
                if (strpos($item['productcode'], 'stourwebcms_app_') !== false) {
                    array_push($result, str_replace('stourwebcms_app_', '', $item['productcode']));
                }
            }
        }
        $tongyong = DB::select()->from("model")->where("maintable='model_archive'")->execute()->as_array();
        if ($tongyong) {
            foreach ($tongyong as $v) {
                array_push($result, 'tongyong_' . $v['pinyin']);
            }
        }

        return $result;
    }

    /**
     * @function 获取uniapp首页可显示的产品列表typeid
     * @param $siteId
     * @param $secret
     * @param string $openTypeIds 已开发的应用
     * @return string
     */
    public static function get_uniapp_product_typeid($siteId, $secret, $openTypeIds)
    {
        $openTypeId = explode(',', $openTypeIds);

        $result        = Model_Api_v2_System::get_xcx_auth(1, $siteId, $secret);
        $productTypeId = Model_Api_v2_System::get_xcx_product_typeid($result);
        $productTypeId = array_unique($productTypeId);
        $typeIds       = array();
        foreach ($productTypeId as $v) {
            if (in_array($v, $openTypeId) || $v > 199) {
                array_push($typeIds, $v);
            }
        }
        $typeIds = implode(',', $typeIds);
        return $typeIds;
    }

    /**
     * @function 通过appCode获取产品typeid 主要用于首页产品展示控制
     * @param $data
     * @return array
     */
    public static function get_xcx_product_typeid($data)
    {
        $p_arr = array(
            "system_line" => 1,
            "system_hotel" => 2,
            "system_car" => 3,
            "system_article" => 4,
            "system_spot" => 5,
            "system_visa" => 8,
            "system_tuan" => 13,
            "system_customize" => 14,
            "system_ship_line" => 104,
            "system_guide" => 106,
            "system_notes" => 101,
            "system_outdoor" => 114,
            "system_news" => 115,
            "system_techan" => 118,
            "system_food" => 121,
            "system_malls" => 21,
            "system_combination" => 23
        );

        $res = array();

        foreach ($data as $v) {
            if (isset($p_arr[$v])) {
                $res[] = $p_arr[$v];
            } else if (strstr($v, 'tongyong')) {
                $pinyin = explode('_', $v);
                $typeid = DB::select('id')->from("model")->where("pinyin='{$pinyin[1]}'")->execute()->get('id');
                if ($typeid) {
                    $res[] = $typeid;
                }

            }
        }
        // 检查导航控制 暂时使用移动端主要航进行控制首页产品展示
        $nav     = DB::select()->from('m_nav')->where('m_isopen', '=', '1')->order_by('m_displayorder',
            'asc')->execute()->as_array();
        $new_res = array();
        foreach ($nav as $v) {
            if (in_array($v['m_typeid'], $res)) {
                $new_res[] = intval($v['m_typeid']);
            }
        }
        return $new_res;
    }

    //处理过滤函数
    function filter_content($content)
    {
        $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/i";
        $content = preg_replace_callback(
            $pattern,
            function ($ma) {
                $newUrl = $ma[1];
                if (strpos($ma[1], 'http') === false) {
                    $newUrl = self::reorganized_resource_url($newUrl);
                }
                return str_replace($ma[1], $newUrl, $ma[0]);
            }, $content);
        return $content;
    }

    /**
     * @param $ico
     * @return array
     * @desc 获取图标数组
     */
    public static function get_ico_list($ico)
    {
        $arr = array();
        if (!empty($ico)) {
            $sql = "SELECT kind,picurl FROM `sline_icon` WHERE id IN($ico)";
            $arr = DB::query(1, $sql)->execute()->as_array();
            foreach ($arr as &$r) {
                $r['litpic'] = Model_Api_V2_System::uniapp_img($r['picurl']);
                // 获取图片宽高
                list($r['width'], $r['height']) = getimagesize($r['litpic']); // 获取图片宽高
            }
        }
        return $arr;
    }

    // 获取应用权限
    public static function get_app_auth($siteId, $secret)
    {

        include_once BASEPATH . "/plugins/api/vendor/xcx/stapi.php";
        //通过api接口获取站点权限
        $method = '/xcxapp/site_auth';
        $params = array(
            'siteId' => $siteId,
            'secret' => $secret
        );

        $api = new Stapi();
        $rtn = $api->http($method, $params);
        return $rtn;
    }

    /**
     * @function 获取最终目的地
     * @param $finaldestid
     * @return string
     */
    public static function get_finaldest_name($finaldestid)
    {
        $name = '';
        if ($finaldestid) {
            $name = DB::select('kindname')->from('destinations')->where('id', '=',
                $finaldestid)->execute()->get('kindname');
        }
        return $name;
    }


}